/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sigodonto.view.managedbean;

import br.com.sigodonto.model.dao.DaoGenerico;
import br.com.sigodonto.model.entity.Clinica;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Fidelis
 */
@ManagedBean
@ViewScoped
public class ConfiguracaoClinicaMB implements Serializable {

    /**
     * Creates a new instance of ConfiguracaoClinicaMB
     */
    private String[] estados = {"Acre", "Alagoas", "Amapá", "Amazonas", "Bahia", "Ceará", "Distrito Federal", "Espírito Santo", "Goiás", "Maranhão",
        "Mato Grosso", "Mato Grosso do Sul", "Minas Gerais", "Pará", "Paraíba", "Paraná", "Pernambuco", "Piauí", "Rio de Janeiro", "Rio Grande do Norte",
        "Rio Grande do Sul", "Rondônia", "Roraima", "Santa Catariana", "São Paulo", "Sergipe", "Tocantins"};
    private Clinica clinica;
    private String tipologo;
    private DaoGenerico daoGenerico;

    public ConfiguracaoClinicaMB() {
        this.daoGenerico = new DaoGenerico();
        this.carregarClinica();
        this.tipologo = "nada";
    }

    public Clinica getClinica() {
        return clinica;
    }

    public void setClinica(Clinica clinica) {
        this.clinica = clinica;
    }

    public String[] getEstados() {
        return estados;
    }

    public void setEstados(String[] estados) {
        this.estados = estados;
    }

    public String getTipologo() {
        return tipologo;
    }

    public void setTipologo(String tipologo) {
        this.tipologo = tipologo;
    }

    public void salvarClinica() {
        FacesMessage message = new FacesMessage();
        String msg = "DADOS DA CLINICA ATUALIZADOS COM SUCESSO!";
        message.setSeverity(FacesMessage.SEVERITY_INFO);

        boolean certo = this.daoGenerico.salvar(this.clinica);

        if (!certo) {
            msg = "ERRO AO ATUALIZAR DADOS DA CLINICA!";
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
        }

        message.setSummary(msg);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public void fileUploadAction(FileUploadEvent event) {
        if (this.tipologo.equals("logo1")) {
            if (this.clinica.getLogo() == null) {
                Calendar c = new GregorianCalendar();
                String[] partesNome = event.getFile().getFileName().split("\\.");

                String nomeArq = "clinica" + c.get(Calendar.DAY_OF_MONTH) + c.get(Calendar.MONTH) + c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR) + c.get(Calendar.MINUTE) + c.get(Calendar.SECOND) + "." + partesNome[1];

                ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
                String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "clinica" + File.separator + nomeArq;

                FileImageOutputStream imageOutput;
                try {

                    this.clinica.setLogo(nomeArq);

                    imageOutput = new FileImageOutputStream(new File(newFileName));
                    imageOutput.write(event.getFile().getContents(), 0, event.getFile().getContents().length);
                    imageOutput.close();


                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
                String caminhoAtualizando = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "clinica" + File.separator + this.clinica.getLogo();

                FileImageOutputStream imageOutput;
                try {


                    imageOutput = new FileImageOutputStream(new File(caminhoAtualizando));
                    imageOutput.write(event.getFile().getContents(), 0, event.getFile().getContents().length);
                    imageOutput.close();


                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (this.tipologo.equals("logo2")) {
            if (this.clinica.getLogo2() == null) {
                Calendar c = new GregorianCalendar();
                String[] partesNome = event.getFile().getFileName().split("\\.");

                String nomeArq = "clinica" + c.get(Calendar.DAY_OF_MONTH) + c.get(Calendar.MONTH) + c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR) + c.get(Calendar.MINUTE) + c.get(Calendar.SECOND) + "." + partesNome[1];

                ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
                String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "clinica" + File.separator + nomeArq;

                FileImageOutputStream imageOutput;
                try {

                    this.clinica.setLogo2(nomeArq);

                    imageOutput = new FileImageOutputStream(new File(newFileName));
                    imageOutput.write(event.getFile().getContents(), 0, event.getFile().getContents().length);
                    imageOutput.close();


                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
                String caminhoAtualizando = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "clinica" + File.separator + this.clinica.getLogo2();

                FileImageOutputStream imageOutput;
                try {


                    imageOutput = new FileImageOutputStream(new File(caminhoAtualizando));
                    imageOutput.write(event.getFile().getContents(), 0, event.getFile().getContents().length);
                    imageOutput.close();


                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (this.tipologo.equals("nada")) {
            FacesMessage message = new FacesMessage();
            String msg = "ESCOLHA O TIPO DA LOGO!";
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary(msg);
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        this.tipologo = "nada";

    }

    private void carregarClinica() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpSession session = (HttpSession) externalContext.getSession(true);
        Clinica clinica1 = (Clinica) session.getAttribute("clinica");
        if (clinica1 != null) {
            this.clinica = clinica1;
        } else {
            this.clinica = new Clinica();
        }
    }
}
